﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Net.Mail;
using System.Configuration;
using System.Web.Security;
using YAF.Core;

public partial class main_uc_forgot_pass : DAO.ESWebUserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        InitializeUI();
    }

    protected override void InitializeUI()
    {
        long langId = DAO.Connection.DEFAULT_LANGUAGE;
        if (Session["language"] != null)
            long.TryParse(Session["language"].ToString(), out langId);

        this.LangId = Convert.ToInt32(langId);
        if (Session["message"] != null && Session["message"] != "")
        {
            ContentPlaceHolder1.Controls.Add(new LiteralControl("<span class='" + Session["message_type_css"].ToString() + "'>"
                    + Session["message"].ToString() + "</span>"));
            Session["message"] = null;
            Session["message_type_css"] = null;
        }
    }
    protected void ESi18nButton1_Click(object sender, EventArgs e)
    {
        if (tb_email.Text != "")
        {
            using (SqlConnection conn = new SqlConnection(DAO.Connection.CONN_STRING1))
            {
                conn.Open();
                using (SqlCommand cmd = new SqlCommand("SELECT * from Fn_GetUserByEmail(@email)", conn))
                {
                    cmd.Parameters.Add("email", tb_email.Text);
                    SqlDataReader dr = cmd.ExecuteReader();
                    if (dr != null)
                    {
                        if (dr.Read())
                        {
                            string pass = DAO.CodeFactory.GetUniqueKey(8);
                            using (SqlCommand cmdUpdate = new SqlCommand("UPDATE Users SET password='" + DAO.CodeFactory.CalcMD5String(pass) + "' WHERE id=" + dr["id"].ToString(), conn))
                            {
                                object val = cmdUpdate.ExecuteNonQuery();
                                if (true/*val != null*/)
                                {
                                    SendEmailToUser(dr["username"].ToString(), pass, dr["Name"].ToString());
                                }
                            }
                        }
                    }
                    dr.Close();
                    Response.Redirect(Request.Url.ToString());
                }
            }   
        }
    }

    private void UpdateForumPassword(string username, string old_pass, string new_pass, out string msg)
    {
        MembershipUser user = Membership.GetUser(username);
        msg = "";
        if (user != null)
        {
            user.ChangePassword(old_pass, new_pass);
            int? userID = RoleMembershipHelper.UpdateForumUser(user, YafContext.Current.PageBoardID);
        }
        else
        {
            msg = "nouser";
        }
    }

    private void SendEmailToUser(string p, string pass, string name)
    {
        string senderMailAdress = ConfigurationManager.AppSettings["senderMailAdress"].ToString();
        string host = ConfigurationManager.AppSettings["host"].ToString();
        //string username = ConfigurationManager.AppSettings["username"].ToString();
        //string password = ConfigurationManager.AppSettings["password"].ToString();

        //create new mail message
        MailMessage mail = new MailMessage();

        //create mail message body
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        mail.IsBodyHtml = true;
        mail.BodyEncoding = System.Text.Encoding.UTF8;

        sb.Append("<html><head>");
        sb.Append("<style> body{font-family: \"Calibri\",\"sans-serif\";font-size: 11pt;margin: 0 0 0.0001pt;}</style>");
        sb.Append("</head><body>");

        sb.Append("Dear " + name + ",");
        sb.Append("<br><br>");
        sb.Append("<p>Your password has been reset and updated on TransrpotExchange.org</p>");
        sb.Append("<p>Your new password is:</p>");
        sb.Append("<strong>Password:</strong> " + pass + "<br>");
        sb.Append("<br>");
        sb.Append("<p>Sincerely,</p><br />");
        sb.Append("<p><font style=\"font-size: 14px; color:#081f59;\"></font><strong>Transportexchange.org</strong><br />");
        sb.Append("</body></html>");
        mail.Body = sb.ToString();

        //set mail message properties
        mail.To.Add(new MailAddress(p));
        //mail.Bcc.Add("ratkop@gmail.com");
        mail.From = new MailAddress(senderMailAdress);
        mail.Subject = "TransportExchange.org Reset Password";

        //create new SmtpClient
        SmtpClient smtpClient = new SmtpClient();

        //set SmtpClient properties
        smtpClient.Port = 25;
        smtpClient.Host = host;
        // for example gmail smtp server
        //smtpClient.Port = Convert.ToInt32(ConfigurationManager.AppSettings["port"]);
        string username = ConfigurationManager.AppSettings["username"].ToString();
        string password = ConfigurationManager.AppSettings["password"].ToString();
        smtpClient.Credentials = new System.Net.NetworkCredential(username, password);

        //send mail message
        try
        {
            smtpClient.Send(mail);
            Session["message"] = " Your password has been updated and send to you on email <br />";
            Session["message_type_css"] = "par_message_ok";
        }
        catch (Exception ex)
        {
            Session["message"] = " An error occured while updateing you password. Reason " + ex.ToString();
            Session["message_type_css"] = "par_message_ok";
        }
    }
}
